#include <stdio.h>
#include "dht11.h"
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"


int H;
TaskFunction_t dht11_handle = NULL;

uint8_t dht11_read_data(void); /* return 0:succeed 1:failed */

void dht11_task(void *pvParam)
{
    while (1)
    {
        dht11_read_data();
        vTaskDelay(pdMS_TO_TICKS(500));
    }
}

void dht11_init(void)
{
    gpio_reset_pin(DHT11_GPIO);
    
    gpio_set_direction(DHT11_GPIO, GPIO_MODE_INPUT_OUTPUT_OD);
    xTaskCreate(dht11_task, "dht11_task", 4096, NULL, 1, &dht11_handle);
}

void dht11_reset(void)
{
    gpio_set_level(DHT11_GPIO, 0);
    ets_delay_us(18000); 
    gpio_set_level(DHT11_GPIO, 1);
    ets_delay_us(17); 
}

uint8_t dht11_check(void)
{
    uint8_t retry = 0, rval = 0;

    while (gpio_get_level(DHT11_GPIO) && retry < 100)
    {
        retry++;
        ets_delay_us(1);
    } 

    if (retry >= 100) 
        rval = 1;
    else
    {
        retry = 0;

        while (!gpio_get_level(DHT11_GPIO) && retry < 100)
        {
            retry++;
            ets_delay_us(1);
        } /* DHT11À­µÍºó»áÔÙ´ÎÀ­¸ßÔ¼87us*/

        if (retry >= 100)
            rval = 1; /* ³¬Ê± */
    }

    return rval;
}

uint8_t dht11_read_bit(void)
{
    uint8_t retry = 0; 

    while (gpio_get_level(DHT11_GPIO) && retry < 100)
    {
        retry++;
        ets_delay_us(1);
    } 

    retry = 0;

    while (!gpio_get_level(DHT11_GPIO) && retry < 100)
    {
        retry++;
        ets_delay_us(1);
    }

    ets_delay_us(40); 

    if (gpio_get_level(DHT11_GPIO))
        return 1;
    else
        return 0;
}

uint8_t dht11_read_byte(void)
{
    uint8_t i, data = 0;

    for (i = 0; i < 8; i++)
    {
        
        data <<= 1;
        
        data |= dht11_read_bit();
    }

    return data;
}

uint8_t dht11_read_data(void) /* return 0:succeed 1:failed */
{
    uint8_t i, buf[5] = {0};
    uint8_t t = 0;
    // uint8_t h = 0;
    uint8_t ret = 1;

    dht11_reset();

    dht11_check();

    for (i = 0; i < 5; i++)
    {
        buf[i] = dht11_read_byte();
    }


    if (buf[4] == (buf[0] + buf[1] + buf[2] + buf[3]))
    {
        H = buf[0];
        t = buf[2];
        ret = 0;
    }

    // printf("T:%d H:%d\r\n", t, H);

    return ret;
}
